<template>
  <div class="kline_box">
    <div class="time_box flex">
      <div
        class="time_item flex_center"
        :class="activeTime.id == item.id ? 'active_time' : ''"
        v-for="(item, index) in timeList"
        :key="index"
        @click="handleChoseTime(item)"
      >
        {{ item.txt }}
      </div>
    </div>
    <!-- k线图 -->
    <div class="k_line" id="k_line_box"></div>
    <div class="flex_between">
      <div class="k_line_box">
        <div
          class="k_line_btn"
          :class="activeMainType == item ? 'k_line_active' : ''"
          v-for="(item, index) in mainIndicators"
          :key="index"
          @click="setMainIndicator(item)"
        >
          {{ item }}
        </div>
      </div>
      <div class="k_line_box">
        <div
          class="k_line_btn"
          :class="activeType == item ? 'k_line_active' : ''"
          v-for="(item, index) in subIndicators"
          :key="index"
          @click="setSubIndicator(item)"
        >
          {{ item }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { dispose, init, registerLocale, utils } from "klinecharts";
import config from "./config";
import { getKlineApi } from "@/api/index";
function getTooltipOptions(candleShowType, candleShowRule, indicatorShowRule) {
  return {
    candle: {
      tooltip: {
        showType: candleShowType,
        showRule: candleShowRule,
        custom: (data) => {
          const { prev, current } = data;
          const prevClose = prev ? prev.close : current.open;
          const change = ((current.close - prevClose) / prevClose) * 100;
        },
      },
    },
    indicator: {
      tooltip: {
        showRule: indicatorShowRule,
      },
    },
  };
}
registerLocale("zh-Hant", {
  time: "時間：",
  open: "開：",
  high: "高：",
  low: "低：",
  close: "收：",
  volume: "成交量：",
});
export default {
  props: ["id"],
  data() {
    return {
      activeTime: {},
      mainIndicators: ["MA", "BOLL", "EMA", "SAR"], // "EMA", "SAR"
      subIndicators: ["VOL", "MA", "MACD", "KDJ"], //"VOL",
      activeMainType: "MA",
      activeType: "VOL",
      lang: localStorage.getItem("lang"),
      data: [],
      opt: {
        customApi: {
          formatDate: (dateTimeFormat, timestamp, format, type) =>
            utils.formatDate(dateTimeFormat, timestamp, this.activeTime.type),
        },
      },
    };
  },
  computed: {
    timeList() {
      return [
        {
          type: "HH:mm",
          id: 1,
          txt: this.$t("分时"),
          value: "1",
        },
        {
          type: "HH:mm",
          id: 8,
          txt: "1min",
          value: "1",
        },
        {
          type: "HH:mm",
          id: 2,
          txt: "5min",
          value: "5",
        }, //min
        {
          type: "HH:mm",
          id: 3,
          txt: "30min",
          value: "30",
        }, //min
        {
          type: "HH:mm",
          id: 4,
          txt: "1h",
          value: "60",
        }, //min
        {
          type: "YYYY-MM-DD",
          id: 5,
          txt: "1d",
          value: "day",
        }, //day
        {
          type: "YYYY-MM-DD",
          id: 6,
          txt: "1w",
          value: "week",
        }, //week
        {
          type: "YYYY-MM",
          id: 7,
          txt: "1m",
          value: "month",
        }, //month
      ];
    },
  },
  mounted: async function () {
    // this.baseUrl = uni.getStorageSync("baseUrl");
    this.chart = init("k_line_box", {
      ...config,
      ...this.opt,
    });
    this.paneId = this.chart.createIndicator("VOL");
    this.activeTime = this.timeList[0];
    // await this.getChartData();
    if (this.lang == "cn") {
      this.chart.setLocale("zh-Hans");
    } else {
      this.chart.setLocale("en");
    }
    this.chart.createIndicator(this.activeMainType, false, {
      id: "candle_pane",
    });
    this.chart.createIndicator(this.activeType, false, {
      id: this.paneId,
    });
    this.chart.setPriceVolumePrecision(5, 3);
    this.changeType();
    this.chart.setStyles({
      grid: {
        horizontal: {
          color: "#222631",
          style: "solid",
        },
        vertical: {
          color: "#222631",
          style: "solid",
        },
      },
      separator: {
        color: "#2e313c",
      },
      xAxis: {
        axisLine: {
          color: "#2e313c",
        },
        tickLine: {
          color: "#2e313c",
        },
      },
      yAxis: {
        axisLine: {
          color: "#2e313c",
        },
        tickLine: {
          color: "#2e313c",
        },
      },
    });
  },
  watch: {
    id(newVal) {
      this.getChartData();
    },
  },
  methods: {
    changeType() {
      if (this.activeTime.id == 1) {
        this.chart.setStyles({
          candle: {
            type: "area",
          },
        });
        this.chart.setStyles(getTooltipOptions("rect", "none", "follow_cross"));
      } else {
        this.chart.setStyles({
          candle: {
            type: "candle_solid",
          },
        });
        this.chart.setStyles(getTooltipOptions("rect", "follow_cross", "follow_cross"));
      }
    },
    async handleChoseTime(time, key) {
      if (this.activeTime.id == time.id) {
        return;
      }
      this.activeTime = this.timeList.filter((item) => {
        return item.id == time.id;
      });
      this.activeTime = this.activeTime[0];
      await this.getChartData();
      this.changeType();
    },
    async getChartData() {
      await getKlineApi({
        token: localStorage.getItem("token"),
        time: this.activeTime.value,
        pro_id: this.id,
      }).then((res) => {
        console.log(res, "<<<<<<<<<<<<<<<<<<<<<<<<<<<,,");
        let data = res.data;
        if (data.length == 0) return;
        data.forEach((item) => {
          this.data.push({
            close: item.close * 1,
            high: item.high * 1,
            low: item.low * 1,
            open: item.open * 1,
            timestamp: item.issuetime * 1000,
            volume: item.volume * 1,
          });
        });
        this.chart.applyNewData(this.data);
      });
    },
    setMainIndicator(name) {
      this.activeMainType = name;
      this.chart.createIndicator({ name: name, precision: 5 }, false, {
        id: "candle_pane",
      });
    },
    setSubIndicator(name) {
      this.chart.createIndicator(name, false, {
        id: this.paneId,
      });
      this.activeType = name;
    },
    unmounted() {
      dispose("k_line_box");
    },
    showMore() {
      this.show = !this.show;
      if (this.show == false) {
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.kline_box {
  width: 100%;
  flex: 1;
  margin-bottom: 5px;
  background: #282b37;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  .time_box {
    // height: 112rpx;

    .time_item {
      flex: 1;
      font-size: 14px;
      font-weight: 400;
      color: hsla(0, 0%, 100%, 0.68);
      position: relative;
      height: 100%;
      margin-bottom: 0.5rem;
      cursor: pointer;
      &::after {
        content: "";
        position: absolute;
        left: 50%;
        bottom: 0;
        width: 40px;
        height: 3px;
        background: transparent;
        border-radius: 4px;
        transform: translateX(-50%);
      }
    }

    .active_time {
      color: #f7d8a7;

      &::after {
        background: #f7d8a7;
      }
    }
  }

  .k_line_box {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    background: transparent;
    font-size: 14px;
    font-weight: 400;
    color: hsla(0, 0%, 100%, 0.68);
    .k_line_btn {
      margin: 5px;
      cursor: pointer;
    }

    .k_line_active {
      color: #f7d8a7;
    }
  }

  .k_line {
    width: 100%;
    flex: 1;
  }
}
.flex {
  display: flex;
  align-items: center;
}
.flex_center {
  display: flex;
  align-items: center;
  justify-content: center;
}
.flex_between {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
